import { readdir, readFile, writeFile } from "fs/promises";
import { resolve } from "path";

const isHtml = (s) => s.endsWith(".html");

const makeLi = (s) => `<li><div class="toc__title">${s}</div></li>`;

const makeA = (s) => `<a href="./${s}"> ${s} </a>`;

const indexFile = resolve("./index.html");

const injectToken = /(<!-- INJECT_BEGIN -->)(.*)(<!-- INJECT_END -->)/;

try {
  const files = await readdir("./");

  let ul = "<ul>";

  for (const file of files) {
    if (isHtml(file)) ul += makeLi(makeA(file));
  }

  ul += "</ul>";

  const indexHtml = await readFile(indexFile, { encoding: "utf-8" });
  const resultHtml = indexHtml.replace(injectToken, `$1${ul}$3`);

  await writeFile(indexFile, resultHtml);

  console.log("Successfully made index.html!");
} catch (error) {
  console.warn(error);
}
